package worker;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;



import utils.AmazonConstants;
import utils.AmazonUtils;
import utils.OCRUtils;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.PropertiesCredentials;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.sqs.AmazonSQSClient;
import com.amazonaws.services.sqs.model.DeleteMessageRequest;
import com.amazonaws.services.sqs.model.Message;
import com.amazonaws.services.sqs.model.ReceiveMessageRequest;
import com.amazonaws.services.sqs.model.SendMessageRequest;
import com.amazonaws.util.StringInputStream;

public class Worker {
	public static void main(String[] args) {
		
		AmazonS3Client s3 = null;
		AmazonSQSClient sqs = null;
		String m2wqURL = null;
		String w2mqURL = null;
		String m2lqURL = null;

		try{
			StringInputStream sip = new StringInputStream(AmazonConstants.AMAZON_CARDENTIALS);
			AWSCredentials credentials = new PropertiesCredentials(sip);
			s3 = new AmazonS3Client(credentials);
			sqs = new AmazonSQSClient(credentials);
			Region usWest2 = Region.getRegion(Regions.US_WEST_2);
			sqs.setRegion(usWest2);
			s3.setRegion(usWest2);
			//creating queues
			m2lqURL = AmazonUtils.createQueue(sqs, AmazonConstants.MANAGER_2_LOCAL_QUEUE_NAME);
			
			m2wqURL = AmazonUtils.createQueue(sqs, AmazonConstants.MANAGER_2_WORKER_QUEUE_NAME);
			w2mqURL = AmazonUtils.createQueue(sqs, AmazonConstants.WORKER_2_MANAGER_QUEUE_NAME);

			OCRUtils ocrScanner = new OCRUtils();
			ArrayList<URL> trainImagesURL = new ArrayList<URL>();
			trainImagesURL.add(new URL("https://s3-us-west-2.amazonaws.com/ass1bucket/trainImages/hpljPica.jpg"));
			trainImagesURL.add(new URL("https://s3-us-west-2.amazonaws.com/ass1bucket/trainImages/ascii.png"));
			trainImagesURL.add(new URL("https://s3-us-west-2.amazonaws.com/ass1bucket/trainImages/digits.jpg"));
			ocrScanner.loadTrainingImages(trainImagesURL);
			
			
			ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(m2wqURL);
			receiveMessageRequest.setVisibilityTimeout(2);
			receiveMessageRequest.setMaxNumberOfMessages(1);
			int msgCounter = 0;

			boolean shouldStop = false;
			while(!shouldStop ){
				List<Message> messages = sqs.receiveMessage(receiveMessageRequest).getMessages();
				if (!messages.isEmpty()){
					Message message = messages.get(0);
					//delete the msg
					String messageRecieptHandle = messages.get(0).getReceiptHandle();
					sqs.deleteMessage(new DeleteMessageRequest(m2wqURL, messageRecieptHandle));
					//taking care of the msg
					msgCounter++;
					System.out.println("  Message");
					System.out.println("    MessageId:     " + message.getMessageId());
					String mBody = message.getBody();
					System.out.println("    Body:          " + mBody);
					for (Entry<String, String> entry : message.getAttributes().entrySet()) 
					{
						System.out.println("  Attribute");
						System.out.println("    Name:  " + entry.getKey());
						System.out.println("    Value: " + entry.getValue());
					}
//					new image task
					String[] tokens = mBody.split(" ");
					if (tokens[0].equals("new") && tokens[1].equals("image") && tokens[2].equals("task")){
						URL url = new URL(tokens[3]);
						// loads the image.
						String s = "";
						try{
							s = ocrScanner.process(url);
							
						}catch (Exception e) {
							s="error: " + e.getMessage();
							e.printStackTrace();
						}
						// prints the results.
		//				System.out.println("RESULTS: \n"+ s.substring(199));
		
						sqs.sendMessage(new SendMessageRequest(w2mqURL, "done image task <img src=\""+tokens[3]+"\" />" + "<p>" + s + "</p><br/>\n"));
					}			
				}else{
					shouldStop = true;					
				}
			}


		}catch (Exception e) {
			error(m2lqURL,"there was an error :" + e.getMessage(),sqs);
			e.printStackTrace();
		}
	}

	private static void error(String qUrl, String msg, AmazonSQSClient sqs) {
		if (sqs != null){
			sqs.sendMessage(new SendMessageRequest(qUrl,"worker error : "  + msg));
		}else{
			System.err.println(msg);
		}
	}
}
